package org.huzhp.gateway.dynamic.rule;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.Set;

/**
 * @Description: 规则控制类
 * @Author: huzp
 * @CreateDate: 2020/3/13 18:01
 * @Version: 1.0
 */
@RestController
@RequestMapping("/gateway/rule")
public class RuleController {

    @Autowired
    private DynamicRuleService dynamicRuleService;

    @GetMapping
    public Set<GatewayFlowRule> get() {
        return dynamicRuleService.getRules();
    }

    @PostMapping
    public Mono<ResponseEntity<Object>> add(@RequestBody GatewayFlowRule rule) {
        try {

            dynamicRuleService.add(rule);
        } catch (Exception e) {
            return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
        }
        return Mono.just(ResponseEntity.ok().build());
    }

    @DeleteMapping("/{resource}")
    public Mono<ResponseEntity<Object>> delete(@PathVariable String resource) {
        try {
            this.dynamicRuleService.delete(resource);
        } catch (Exception e) {
            return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
        }
        return Mono.just(ResponseEntity.ok().build());
    }

    @DeleteMapping
    public Mono<ResponseEntity<Object>> delete(@RequestBody GatewayFlowRule rule) {
        try {
            this.dynamicRuleService.delete(rule);
        } catch (Exception e) {
            return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
        }
        return Mono.just(ResponseEntity.ok().build());
    }
}
